import os
from xml.etree import ElementTree
import xml
import stat


def listdir(path):
    for filename in os.listdir(path):
        yield os.path.join(path, filename)


def walk(path='.', depth=5):
    # ref: https://gist.github.com/bpeterso2000/8033539
    if depth and depth == 1:
        for filename in listdir(path):
            yield filename
    else:
        top_pathlen = len(path) + len(os.path.sep)
        for dirpath, dirnames, filenames in os.walk(path):
            dirlevel = dirpath[top_pathlen:].count(os.path.sep)
            if depth and dirlevel >= depth:
                dirnames[:] = []
            if dirlevel >= 5 and '.idea' not in [dirpath] + dirnames + filenames:
                dirnames[:] = []
            else:
                for filename in filenames:
                    yield os.path.join(dirpath, filename)


def modify_xml(folder_name):
    for f in walk('..' + os.sep + '..' + os.sep + folder_name + os.sep, 5):
        try:
            if '.idea' in f and f.endswith('workspace.xml'):
                xml_file = f

                root = ElementTree.parse(xml_file).getroot()

                HAS_GIT_SETTINGS = 0
                HAS_PREVIEW_PUSH_ON_COMMIT_AND_PUSH = 0
                HAS_CHECK_NEW_TODO = 0
                MODIFIED = 0

                for component in root:
                    if str(component.attrib) == '{\'name\': \'Git.Settings\'}':
                        HAS_GIT_SETTINGS = 1
                        for option in component:
                            if 'PREVIEW_PUSH_ON_COMMIT_AND_PUSH' in str(option.attrib):
                                HAS_PREVIEW_PUSH_ON_COMMIT_AND_PUSH += 1
                                if option.get('value') == 'true':
                                    option.set('value', 'false')
                                    MODIFIED = 1
                                    # option.attrib.pop('PREVIEW_PUSH_ON_COMMIT_AND_PUSH')
                        if HAS_PREVIEW_PUSH_ON_COMMIT_AND_PUSH == 0:
                            option = xml.etree.ElementTree.SubElement(
                                component, 'option',
                                attrib={'name': 'PREVIEW_PUSH_ON_COMMIT_AND_PUSH',
                                        'value': 'false'})
                            MODIFIED = 1

                    if str(component.attrib) == '{\'name\': \'VcsManagerConfiguration\'}':
                        for option in component:
                            if 'CHECK_NEW_TODO' in str(option.attrib):
                                HAS_CHECK_NEW_TODO += 1
                                if option.get('value') == 'true':
                                    option.set('value', 'false')
                                    MODIFIED = 1
                        if HAS_CHECK_NEW_TODO == 0:
                            option = xml.etree.ElementTree.SubElement(
                                component, 'option',
                                attrib={'name': 'CHECK_NEW_TODO',
                                        'value': 'false'})
                            MODIFIED = 1

                if HAS_GIT_SETTINGS == 0:
                    component = xml.etree.ElementTree.SubElement(
                            root, 'component',
                            attrib={'name': 'Git.Settings'})
                    option = xml.etree.ElementTree.SubElement(
                        component, 'option',
                        attrib={'name': 'PREVIEW_PUSH_ON_COMMIT_AND_PUSH',
                                'value': 'false'})
                    MODIFIED = 1

                if MODIFIED == 1:
                    tree = xml.etree.ElementTree.ElementTree(root)

                    if os.path.isfile(xml_file):
                        os.chmod(xml_file, stat.S_IWRITE)
                        os.remove(xml_file)
                    else:
                        print("Error: %s file not found" % xml_file)
                    tree.write(xml_file, encoding="UTF-8", xml_declaration=True)
        except:
            pass


def main():
    for _folder_name in ['PycharmProjects', 'IdeaProjects',
                         'WebstormProjects', 'CLionProjects',
                         'PhpstormProjects', 'PhpProjects',
                         'gohugo', 'RubymineProjects', 'Documents' + os.sep + 'GitHub']:
        try:
            modify_xml(_folder_name)
        except:
            pass



if __name__ == "__main__":
    try:
        os.chdir(os.path.dirname(os.path.abspath(__file__)))
        main()
    except:
        pass
    try:
        os.chdir("D:\\CLionProjects\\adblockplus")
        main()
    except:
        pass


